<?php

declare( strict_types = 1 );

namespace App\Common\Model\Base;

use App\Common as com;
use App\Common\Model\Base as nameBase;

class DataManager extends nameBase\DataManager\MainV3 {

	/**
	 * @param string $dataUnitClassPath
	 * @param array|null $assignWhere
	 * @return mixed
	 */
	protected function goParentOfClassName( string $dataUnitClassPath, array $assignWhere = null ) {
		// ...
		$where = null;
		//
		if( ! $this->isCreate() ){
			if( $assignWhere !== null ){
				$where = $assignWhere;
			}else{
				$where = $this->getParentWhere();
			}
		}
		//
		return $this->goPoolParam( __FUNCTION__, $dataUnitClassPath, function () use ( $dataUnitClassPath, $where ){
			return $this->newOfDataUnitClassName( $dataUnitClassPath, [ $where ] );
		} );
	}

	/**
	 * goClient
	 * @param string $dataUnitClassPath
	 * @param array|null $assignWhere
	 * @return mixed
	 */
	protected function goClientOfClassName( string $dataUnitClassPath, array $assignWhere = null ) {
		// ...
		$where = null;
		//
		if( $this->isUpdate() ){
			if( $assignWhere !== null ){
				$where = $assignWhere;
			}else{
				$where = [ $this->relevanceDataFieldMapOfClient[1] => $this->getMainDataIdOfClient() ];
			}
		}
		//
		return $this->goPoolParam( __FUNCTION__, $dataUnitClassPath, function () use ( $dataUnitClassPath, $where ){
			return $this->newOfDataUnitClassName( $dataUnitClassPath, [ $where ] )->injectParent( $this, false );
		} );
	}

	/**
	 * @param string $dataUnitClassPath
	 * @param array|null $param
	 * @return DataManager
	 */
	private function newOfDataUnitClassName( string $dataUnitClassPath, array $param = null ):nameBase\DataManager {
		return new $dataUnitClassPath( ...$param );
	}

	/**
	 * dataManager保存
	 * @param com\Model\Base\DataManager $dataManager
	 * @param int $mainDataIdOfClient
	 */
	public function saveClient( com\Model\Base\DataManager $dataManager, int $mainDataIdOfClient ) {
		if( $this->isCreate() ) {
			// 创建
			$dataManager->goDataset()->set( com\Lib\Fun\Str::parseName( $dataManager->getMainDataFieldNameRawOfParent(), 1, false ), $mainDataIdOfClient );
		}else{
			// 更新
			$dataManager->goModelQuery()->where( $dataManager->getMainDataFieldNameRawOfParent(), $mainDataIdOfClient );
		}
		// 保存
		$dataManager->saveAll();
	}

}
